/* eslint-disable no-param-reassign */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Message, Input } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid } from '../stores/definitions';
import moment from 'moment';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },
  wrapperCol: {
    span: 17,
  },
  style: { marginBottom: 20 },
};

function SendNotify({ activity, modal, onSubmit, onCancel }) {
  const { activityStore: store } = useStore();
  const [notify] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [recipients, setRecipients] = useState([]);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (JSON.stringify(activity) !== '{}') {
      (async () => {
        const data = await store.get(activity?.id);
        const beginTime = data?.announcement?.beginTime || null;
        const endTime = data?.announcement?.endTime || null;
        editCtx.origin = _.cloneDeep(data);
        _.assign(notify, data);
        _.set(notify, 'notify.timeRange', [moment(beginTime).add('8', 'hours').format('YYYY-MM-DD'), moment(endTime).add('8', 'hours').format('YYYY-MM-DD')]);
        _.set(notify, 'notify.popupType', '0');
        _.set(notify, 'notify.recipients', []);
      })();
    }
  }, []);

  if (!notify) return <></>;

  const overrideModel = {
    notify: {
      recipients: {
        ui: {
          renderer: (v) => (
            <TauSimpleSelect value={v} mode="multiple" dataSource={recipients} />
          ),
        },
      },
      addRecipients: {
        ui: {
          renderer: () => (
            <Input
              placeholder="请输入手机号"
              addonAfter={<Button type="primary" onClick={handleAddUser}>{t`添加为接收者`}</Button>}
            />
          ),
        },
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(notify, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleAddUser = async () => {
    const { addRecipients } = notify.notify;
    if (!addRecipients) {
      return Message.warning({ content: t`请输入用户或者手机号!` });
    }
    const findUser = recipients?.find((p) => p.value.startsWith(addRecipients));
    if (findUser) {
      return Message.warning({ content: t`该用户已存在!` });
    }
    if (addRecipients === 'admin') {
      setRecipients((pre) => {
        const arr = [...pre];
        arr.push({ label: t`admin控制台`, value: 'admin@mzd' });
        return arr;
      });
      _.set(notify, 'notify.recipients', notify.notify.recipients.concat(['admin@mzd']));
      return;
    }
    try {
      const res = await store.getUserMobile(addRecipients);
      if (res) {
        setRecipients((pre) => {
          const arr = [...pre];
          arr.push({ label: res.fullname, value: res.username });
          return arr;
        });
        _.set(notify, 'notify.recipients', notify.recipients.concat([res.username]));
      } else {
        Message.error({ content: t`该用户非平台用户!` });
      }
    } catch (error) {
      Message.error({ content: t`添加失败`, duration: 7000 });
      throw error;
    }
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: SendNotify.jsx:131 _ errors:', errors);
      return;
    }
    const { notifyType: type, subject, content, notifySendTypes: sendTypes, popupType, recipients: users } = notify?.notify || {};
    const params = {
      recipients: users,
    };
    params.notificationRequest = {
      type,
      businessKey: activity?.id,
      subject,
      content,
      sendTypes,
      params: {
        popupType,
      },
    };
    onSubmit?.(params);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={notify}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
      style={{ marginTop: 20 }}
    >
      <FieldsGrid
        formData={notify}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={1}
        overrideModel={overrideModel}
        fields={['subject', 'notifyType', 'notifySendTypes',
          'popupType', 'addRecipients',
          'recipients', 'content',
        ].map((p) => `notify.${p}`)}
      />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

    </Form>
  );
}

export default observer(SendNotify);

